<template>
  <div class="app-container table-app-container">
    <div class="fixed-table">
      <div class="fixed-table-actionbar">
        <TableFilter />
        <ActionBar />
      </div>
      <PageableTable
        :loading="loading"
        :data="insideTableData"
        :total="totalElements"
        :page="currentPage"
        :page-size="pageSize"
        :table-height="tableHeight"
        class="fixed-table-table"
        @page-change="onPageChange"
        @sort-change="onSortChange"
      >
        <el-table-column v-for="column in insideColumns" :key="column.key" :label="column.title" :prop="column.key" :sortable="column.sortable">
          <template slot-scope="scope">
            <column-render :render="column.render" :row="scope.row" :column="column" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
          <template slot-scope="{row}">
            <el-button type="text" size="mini" icon="el-icon-edit" title="编辑" @click="edit(row.id)" />
            <el-button type="text" size="mini" icon="el-icon-delete" title="删除" @click="remove(row.id)" />
            <el-button type="text" size="mini" icon="el-icon-key" title="编辑流程模板" @click="editProcess(row)" />
            <el-button v-if="row.isExist" type="text" size="mini" icon="el-icon-download" title="导出" @click="download(row)" />
            <el-upload
              :headers="headers"
              :action="action()"
              :before-upload="handleBeforeUpLoad"
              :on-success="handleSuccess"
              :on-error="handleError"
              :show-file-list="false"
              style="display:inline-block; margin-left: 10px;"
            >
              <el-button title="上传模板" size="mini" type="text" icon="el-icon-upload2" @click="currentRowCode=row.code" />
            </el-upload>

          </template>
        </el-table-column>
      </PageableTable>
    </div>
    <FormDialog title="编辑" :show.sync="dialogFormVisible" width="40%" @on-ok="ok" @on-cancel="cancel">
      <EditForm :id="editId" ref="editForm" />
    </FormDialog>
  </div>
</template>

<script>
// secondary package based on el-pagination
import FormDialog from '@neu/biz-core/components/FormDialog'
// 表格查询组件独立编写，需要传递pageable-table实例的mixin方法filter
import TableFilter from './components/tableFilter'
// 编辑实例组件独立编写，需要传递id属性，判断新建还是更新操作
import EditForm from './components/editForm'
import ActionBar from './components/actionBar'
import PageableTable from '@neu/biz-core/components/PageableTable'
import databind from '@neu/biz-core/mixins/databind'
import { list as dList } from '@neu/dcam-ui/api/dictionary'
import { exportBpmn, uploadUrl } from '@neu/dcam-ui/api/workflowDefinition'
import { getToken } from '@neu/biz-core/utils/auth'
import {
  page,
  remove
} from '@neu/dcam-ui/api/process'
export default {
  name: 'ProcessPage',
  components: {
    TableFilter,
    FormDialog,
    EditForm,
    ActionBar,
    PageableTable
  },
  // 加入混入，使表格混入更多的api操作
  mixins: [databind],
  data() {
    return {
      r: page,
      d: remove,
      insideColumns: [
        {
          title: '名称',
          key: 'name',
          sortable: 'custom'
        },
        {
          title: '工单类型',
          key: 'type',
          render: (h, params) => {
            const data = this.workTypeList.filter(s => s.code === params.row.code)
            const text = data.length > 0 ? data[0].text : ''
            return h('span', [
              h('span', text)
            ])
          }
        },
        {
          title: '工单编码',
          key: 'code'
        }
      ],
      workTypeList: [],
      dialogFormVisible: false,
      dialogStatus: 'create',
      editId: -1,
      importUrl: uploadUrl,
      headers: {
        'Access-Control-Allow-Origin': '*',
        'Authentication': getToken()
      },
      currentRowCode: ''
    }
  },
  created() {
    this.fetch()
    dList({ s_type: 'workorderType' }).then(res => { this.workTypeList = res.data })
  },
  methods: {
    // 表格编辑按钮点击事件处理
    edit(id) {
      // 打开对话框
      this.editId = id
      this.dialogFormVisible = true
      // 更新当前被编辑实体的ID，自动传递至编辑表单
    },
    // 编辑资产对话框确认事件处理
    ok() {
      // 直接调用表单实例的保存方法
      this.$refs.editForm.save().then(response => {
        if (response === false) return
        this.$message({
          showClose: true,
          message: '操作成功！',
          type: 'success'
        })
        // 调用pageable-table实例的mixin方法refresh()，更新表格
        this.refresh()
        // 关闭对话框
        this.dialogFormVisible = false
      })
    },
    cancel() {
      this.editId = -1
      this.$refs.editForm.reset()
      // 关闭对话框
      this.dialogFormVisible = false
    },
    editProcess(row) {
      this.$router.push({ name: 'dcam_workflowEdit', params: { 'id': row.code, 'name': row.name, 'isExist': row.isExist }})
    },
    handleBeforeUpLoad(file) {
    },
    handleSuccess(response, file, fileList) {
      if (response.status === 'failure') {
        this.$message({
          showClose: true,
          message: response.data,
          type: 'error'
        })
      } else {
        this.$message({
          showClose: true,
          message: '文件上传成功',
          type: 'success'
        })
        this.refresh()
      }
    },
    handleError() { },
    download(row) {
      exportBpmn(row.code).then(res => {
        const content = res.data
        const blob = new Blob([content])
        const fileName = row.name + '.bpmn'
        if ('download' in document.createElement('a')) { // 非IE下载
          const elink = document.createElement('a')
          elink.download = fileName
          elink.style.display = 'none'
          elink.href = URL.createObjectURL(blob)
          document.body.appendChild(elink)
          elink.click()
          URL.revokeObjectURL(elink.href) // 释放URL 对象
          document.body.removeChild(elink)
        } else { // IE10+下载
          navigator.msSaveBlob(blob, fileName)
        }
      })
    },
    action() {
      return this.importUrl + '/' + this.currentRowCode
    }
  }
}
</script>
